package framework.helpers;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import framework.ApplicationManager;
import framework.entities.AppointmentData;

public class AppointmentsHelper extends BaseHelperForRmis
{
    private List<WebElement> listOfAppointment;

	public AppointmentsHelper(ApplicationManager app) {
        super(app);
    }

	/**
	 * Вводит данные и запускает поиск предварительной записи
	 *
	 * @param appointmentData данные предварительной записи
	 */
	public void findAppointment(AppointmentData appointmentData) {
		log.info("Поиск назначения: " + appointmentData);
		app.getNavigationHelper().goToAppointments();
		chooseMedicalOrganization(appointmentData.medicalOrganization);
		chooseExecutor(appointmentData.executor);
		chooseStatus();
		choosePatient(appointmentData.patient);
		chooseDate(appointmentData.getDateWithoutTime());
		click(By.cssSelector(".lsd-buttons-panel [title='Найти'] a"));
	}

	private void chooseMedicalOrganization(String medicalOrganization) {
    	selectFirstInCombobox(By.id("organizationIdContainer"), medicalOrganization);
	}
	
	private void chooseExecutor(String executor) {
		 click(By.xpath("//div[@id='executorIdContainer']/div/div"));
		 typeAndSelectByNumber(By.name("_executorIdEdit"), executor, 0);
	}
	
	private void chooseStatus() {
		click(By.xpath("//*[@id='statusId']/div[1]/div[3]/input"));
	}	

	private void choosePatient(String patient) {
	 	click(By.xpath("//div[@id='individual.quick.search0Container']/div/div"));
	 	typeAndSelectByNumber(By.name("_individual.quick.search0Edit"), patient, 0);
	}
	
	private void chooseDate(String date) {
		type(By.id("dateInterval.from"), date);
		type(By.id("dateInterval.to"), date);
	}	

	/**
	 * Открывает первую в таблице предварительную запись для редактирования
	 */
	public void startFormalities() {
		log.info("Открытие назначения на редактирование.");
		int appointmentNumber = 0;
		chooseAppointment(appointmentNumber);
	}	

	private void chooseAppointment(int appointmentNumber) {
		WebElement appointmentElement = getListOfAppointment().get(appointmentNumber);
		click(appointmentElement);
		click(By.cssSelector("[title='Оформить прием'] a"));
	}
	
	private List<WebElement> getListOfAppointment() {
		waitWhileAjaxCompleted();
		if (listOfAppointment == null)
			listOfAppointment = findElements(By.cssSelector(".x-grid-row"));
		return listOfAppointment;
	}	
	
	/**
	 * Заполняет данные посещения и сохраняет изменения
	 */
	public void completeFormalities() {
		log.info("Заполнение полей назначения.");
		chooseFundingSourceType();
		chooseComplexityLevel();
		chooseInitGoal();
		choosePaymentMethod();
		inputCurrentDate();
		chooseVisitGoal();
		chooseProfile();
		chooseCaseDiagnoses();
		clickSaveButton();
	}

	private void chooseProfile() {
	 	click(By.xpath("//*[@id='visit.profile.idContainer']/div/div"));
    	typeAndSelectByNumber(By.name("visit.profile.name"), "", 0);
	}

	private void chooseCaseDiagnoses() {
		click(By.xpath("(//a[contains(text(),'Добавить')])[4]"));
		chooseFirstHospitalRecordCaseDiagnoses();
	}

	private void chooseFirstHospitalRecordCaseDiagnoses() {
    	click(By.xpath("//*[@id='visit.caseDiagnoses$diagnos.idContainer']/div/div"));
    	typeAndSelectByNumber(By.name("_visit.caseDiagnoses$diagnos.idEdit"), "", 0);
    	click(By.xpath("(//a[contains(text(),'Сохранить')])[8]"));
	}

	private void chooseComplexityLevel() {
		click(By.cssSelector("#complexityLevel-to-show a"));
		click(By.xpath("//*[@id='medicalCase.complexityLevel.idContainer']/div/div"));
    	typeAndSelectByNumber(By.name("_medicalCase.complexityLevel.idEdit"), "", 0);
	}

	private void chooseFundingSourceType() {
    	click(By.xpath("//*[@id='medicalCase.fundingSourceType.idContainer']/div/div"));
    	typeAndSelectByNumber(By.name("medicalCase.fundingSourceType.name"), "", 0);
	}
	
	private void chooseInitGoal() {
    	click(By.xpath("//*[@id='medicalCase.initGoal.idContainer']/div/div"));
    	typeAndSelectByNumber(By.name("medicalCase.initGoal.name"), "", 0);
	}

	private void choosePaymentMethod() {
    	click(By.xpath("//*[@id='medicalCase.paymentMethod.idContainer']/div/div"));
    	typeAndSelectByNumber(By.name("medicalCase.paymentMethod.name"), "", 0);
	}
	
	private void inputCurrentDate() {
    	By admissionDate = By.id("visit.admissionDate");
    	click(admissionDate);
    	type(admissionDate, getCurrentDate());
	}
	
	private void chooseVisitGoal() {
    	click(By.xpath("//*[@id='visit.goal.idContainer']/div/div"));
    	typeAndSelectByNumber(By.name("visit.goal.name"), "", 0);
	}
	
	/**
	 * Возвращает количество записей в таблице
	 *
	 * @return количество записей в таблице
	 */
	public int getCountOfRecord(){
		return getListOfGrid().size();
	}

	/**
	 * Возвращает информацию о докторе исполнителе
	 *
	 * @return информация о докторе
	 */	
	public String getExecutor() {
		return findElement(By.xpath(".//*[@id='visit.resourceGroup.idContainer']/div/div")).getText();
	}

	/**
	 * Возвращает наименование услуги
	 *
	 * @return наименование услуги
	 */	
	public String getService() {
		String serviceWithId = findElement(By.cssSelector(".lsd-table-rows>table>tbody>tr>td")).getText();
		return serviceWithId.substring(serviceWithId.indexOf(" ")).trim();
	}
}
